package com.healthfitness.floating.service

import android.content.Intent
import android.graphics.PixelFormat
import android.view.Gravity
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.WindowManager
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.ui.platform.ComposeView
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalSavedStateRegistryOwner
import androidx.lifecycle.LifecycleService
import androidx.lifecycle.ViewModelStore
import androidx.lifecycle.ViewModelStoreOwner
import androidx.lifecycle.setViewTreeLifecycleOwner
import androidx.lifecycle.setViewTreeViewModelStoreOwner
import androidx.savedstate.SavedStateRegistry
import androidx.savedstate.SavedStateRegistryController
import androidx.savedstate.SavedStateRegistryOwner
import androidx.savedstate.setViewTreeSavedStateRegistryOwner
import com.healthfitness.floating.R
import com.healthfitness.floating.ui.compose.FloatingContent
import com.healthfitness.floating.ui.listener.DragMoveListener

class FloatingService : LifecycleService(), SavedStateRegistryOwner {
    private lateinit var windowManager: WindowManager
    private lateinit var floatingView: View
    private lateinit var composeView: ComposeView
    private val mViewModelStore = ViewModelStore()
    private val mViewModelStoreOwner = object : ViewModelStoreOwner {
        override val viewModelStore: ViewModelStore
            get() = mViewModelStore
    }
    private val savedStateRegistryController = SavedStateRegistryController.create(this)
    override val savedStateRegistry: SavedStateRegistry =
        savedStateRegistryController.savedStateRegistry

    override fun onCreate() {
        super.onCreate()
        windowManager = getSystemService(WINDOW_SERVICE) as WindowManager
        savedStateRegistryController.performAttach()
        savedStateRegistryController.performRestore(null)
        createFloatingView()
        createComposeView()
    }

    private fun createComposeView() {

        val params = WindowManager.LayoutParams(
            WindowManager.LayoutParams.WRAP_CONTENT,
            WindowManager.LayoutParams.WRAP_CONTENT,
            WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
            WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS or WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN,
            PixelFormat.TRANSLUCENT
        ).apply {
            gravity = Gravity.BOTTOM or Gravity.CENTER
            x = 0
            y = 0
        }

        // 用 ComposeView 来承载 Compose内容
        composeView = ComposeView(this).apply {
            // 绑定到 Application 生命周期（替代 ViewTreeLifecycleOwner）
            setViewTreeLifecycleOwner(this@FloatingService)
            setViewTreeViewModelStoreOwner(mViewModelStoreOwner)
            setViewTreeSavedStateRegistryOwner(this@FloatingService)


            setContent {
                CompositionLocalProvider(
                    LocalSavedStateRegistryOwner provides this@FloatingService,
                    LocalContext provides this@FloatingService
                ) {
                    FloatingContent()
                }
            }


            setOnTouchListener(DragMoveListener(windowManager))
        }
        windowManager.addView(composeView, params)
    }

    private fun createFloatingView() {
        val params = WindowManager.LayoutParams(
            WindowManager.LayoutParams.WRAP_CONTENT,
            WindowManager.LayoutParams.WRAP_CONTENT,
            WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
            WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
            PixelFormat.TRANSLUCENT
        ).apply {
            gravity = Gravity.TOP or Gravity.START
            x = 0
            y = 0
        }

        floatingView = LayoutInflater.from(this).inflate(R.layout.float_window, null)
        windowManager.addView(floatingView, params)

        // 点击打开应用
        floatingView.findViewById<View>(R.id.btn_float).setOnClickListener {
            val intent = packageManager.getLaunchIntentForPackage(packageName)
            intent?.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            startActivity(intent)
            stopSelf()//关闭浮窗
        }
    }


    override fun onDestroy() {
        super.onDestroy()
        mViewModelStore.clear()
        if (::floatingView.isInitialized) {
            windowManager.removeView(floatingView)
        }
        if (::composeView.isInitialized) {
            windowManager.removeView(composeView)
        }
    }


}